﻿using System;
using System.IO;
using System.Security.Cryptography;

namespace PhotoManager
{
    public class ContentHash :
        IEquatable<ContentHash>,
        IComparable<ContentHash>
    {
        private readonly string m_hash;

        public ContentHash(string hash)
        {
            if (hash == null)
                throw new ArgumentNullException("hash");
            m_hash = hash;
        }

        public static ContentHash Compute(string fileName)
        {
            if (fileName == null)
                throw new ArgumentNullException("fileName");

            using (Stream stream = File.OpenRead(fileName))
            using (SHA256 hasher = new SHA256Managed())
            {
                byte[] hash = hasher.ComputeHash(stream);
                return new ContentHash(BitConverter.ToString(hash).Replace("-", ""));
            }
        }

        public override int GetHashCode()
        {
            return m_hash.GetHashCode();
        }

        public override string ToString()
        {
            return m_hash;
        }

        public static ContentHash Parse(string s)
        {
            if (s == null)
                throw new ArgumentNullException("s");
            return new ContentHash(s);
        }

        public bool Equals(ContentHash other)
        {
            return this.m_hash == other.m_hash;
        }

        public int CompareTo(ContentHash other)
        {
            return this.m_hash.CompareTo(other.m_hash);
        }
    }
}
